import { ref, onMounted, onUnmounted } from 'vue'
import { gsap } from 'gsap'

export interface GestureConfig {
  threshold?: number
  velocity?: number
  direction?: 'horizontal' | 'vertical' | 'both'
  enableSwipe?: boolean
  enablePinch?: boolean
  enableTap?: boolean
}

export interface TouchPoint {
  x: number
  y: number
  timestamp: number
}

export const useMobileGestures = (
  element: any,
  config: GestureConfig = {}
) => {
  const {
    threshold = 50,
    velocity = 0.3,
    direction = 'both',
    enableSwipe = true,
    enablePinch = true,
    enableTap = true,
  } = config

  // 状态
  const isTouch = ref(false)
  const touchStartPoint = ref<TouchPoint | null>(null)
  const touchCurrentPoint = ref<TouchPoint | null>(null)
  const touchDistance = ref(0)
  const touchAngle = ref(0)
  const initialPinchDistance = ref(0)
  const currentScale = ref(1)

  // 事件回调
  const swipeCallbacks = {
    left: [] as Function[],
    right: [] as Function[],
    up: [] as Function[],
    down: [] as Function[],
  }

  const pinchCallbacks = {
    start: [] as Function[],
    move: [] as Function[],
    end: [] as Function[],
  }

  const tapCallbacks = {
    single: [] as Function[],
    double: [] as Function[],
    long: [] as Function[],
  }

  // 工具函数
  const getDistance = (p1: TouchPoint, p2: TouchPoint): number => {
    const dx = p2.x - p1.x
    const dy = p2.y - p1.y
    return Math.sqrt(dx * dx + dy * dy)
  }

  const getAngle = (p1: TouchPoint, p2: TouchPoint): number => {
    const dx = p2.x - p1.x
    const dy = p2.y - p1.y
    return Math.atan2(dy, dx) * (180 / Math.PI)
  }

  const getPinchDistance = (touches: TouchList): number => {
    if (touches.length < 2) return 0
    const touch1 = touches[0]
    const touch2 = touches[1]
    const dx = touch2.clientX - touch1.clientX
    const dy = touch2.clientY - touch1.clientY
    return Math.sqrt(dx * dx + dy * dy)
  }

  const getTouchPoint = (touch: Touch): TouchPoint => ({
    x: touch.clientX,
    y: touch.clientY,
    timestamp: Date.now(),
  })

  // 触摸开始
  const handleTouchStart = (event: TouchEvent) => {
    if (!element.value) return

    isTouch.value = true
    const touch = event.touches[0]
    touchStartPoint.value = getTouchPoint(touch)
    touchCurrentPoint.value = touchStartPoint.value

    // 处理多点触控（缩放）
    if (enablePinch && event.touches.length === 2) {
      initialPinchDistance.value = getPinchDistance(event.touches)
      pinchCallbacks.start.forEach(cb => cb(event))
    }

    // 添加触摸反馈
    addTouchFeedback(element.value, touch.clientX, touch.clientY)
  }

  // 触摸移动
  const handleTouchMove = (event: TouchEvent) => {
    if (!element.value || !touchStartPoint.value) return

    event.preventDefault()
    const touch = event.touches[0]
    touchCurrentPoint.value = getTouchPoint(touch)

    touchDistance.value = getDistance(touchStartPoint.value, touchCurrentPoint.value)
    touchAngle.value = getAngle(touchStartPoint.value, touchCurrentPoint.value)

    // 处理缩放手势
    if (enablePinch && event.touches.length === 2) {
      const currentPinchDistance = getPinchDistance(event.touches)
      const scale = currentPinchDistance / initialPinchDistance.value
      currentScale.value = scale

      pinchCallbacks.move.forEach(cb => cb({
        scale,
        distance: currentPinchDistance,
        event,
      }))
    }
  }

  // 触摸结束
  const handleTouchEnd = (event: TouchEvent) => {
    if (!element.value || !touchStartPoint.value || !touchCurrentPoint.value) return

    isTouch.value = false

    // 处理滑动手势
    if (enableSwipe && touchDistance.value > threshold) {
      const timeDiff = touchCurrentPoint.value.timestamp - touchStartPoint.value.timestamp
      const currentVelocity = touchDistance.value / timeDiff

      if (currentVelocity > velocity) {
        const angle = touchAngle.value
        let swipeDirection: string

        if (direction === 'horizontal' || direction === 'both') {
          if (angle > -45 && angle < 45) {
            swipeDirection = 'right'
          } else if (angle > 135 || angle < -135) {
            swipeDirection = 'left'
          }
        }

        if (direction === 'vertical' || direction === 'both') {
          if (angle > 45 && angle < 135) {
            swipeDirection = 'down'
          } else if (angle > -135 && angle < -45) {
            swipeDirection = 'up'
          }
        }

        if (swipeDirection! && swipeCallbacks[swipeDirection as keyof typeof swipeCallbacks]) {
          swipeCallbacks[swipeDirection as keyof typeof swipeCallbacks].forEach(cb => cb({
            direction: swipeDirection,
            distance: touchDistance.value,
            velocity: currentVelocity,
            angle: touchAngle.value,
            event,
          }))
        }
      }
    }

    // 处理点击手势
    if (enableTap && touchDistance.value < 10) {
      handleTap(event)
    }

    // 处理缩放结束
    if (enablePinch && initialPinchDistance.value > 0) {
      pinchCallbacks.end.forEach(cb => cb({
        scale: currentScale.value,
        event,
      }))
    }

    // 重置状态
    touchStartPoint.value = null
    touchCurrentPoint.value = null
    touchDistance.value = 0
    touchAngle.value = 0
    initialPinchDistance.value = 0
    currentScale.value = 1
  }

  // 处理点击
  let lastTapTime = 0
  let tapTimeout: number

  const handleTap = (event: TouchEvent) => {
    const currentTime = Date.now()
    const timeDiff = currentTime - lastTapTime

    if (timeDiff < 300) {
      // 双击
      clearTimeout(tapTimeout)
      tapCallbacks.double.forEach(cb => cb(event))
    } else {
      // 单击（延迟执行以检测双击）
      tapTimeout = setTimeout(() => {
        tapCallbacks.single.forEach(cb => cb(event))
      }, 300)
    }

    lastTapTime = currentTime
  }

  // 长按处理
  let longPressTimeout: number

  const handleLongPress = (event: TouchEvent) => {
    longPressTimeout = setTimeout(() => {
      if (isTouch.value && touchDistance.value < 10) {
        tapCallbacks.long.forEach(cb => cb(event))
      }
    }, 500)
  }

  // 添加触摸反馈效果
  const addTouchFeedback = (element: Element, x: number, y: number) => {
    const feedback = document.createElement('div')
    feedback.className = 'touch-feedback'
    
    const rect = element.getBoundingClientRect()
    const localX = x - rect.left
    const localY = y - rect.top

    feedback.style.cssText = `
      position: absolute;
      left: ${localX}px;
      top: ${localY}px;
      width: 40px;
      height: 40px;
      border-radius: 50%;
      background: rgba(14, 165, 233, 0.3);
      pointer-events: none;
      z-index: 1000;
      transform: translate(-50%, -50%) scale(0);
    `

    element.appendChild(feedback)

    // 动画效果
    gsap.to(feedback, {
      scale: 1,
      duration: 0.2,
      ease: 'power2.out',
      onComplete: () => {
        gsap.to(feedback, {
          scale: 0,
          opacity: 0,
          duration: 0.3,
          ease: 'power2.in',
          onComplete: () => {
            if (feedback.parentNode) {
              feedback.parentNode.removeChild(feedback)
            }
          }
        })
      }
    })
  }

  // 事件注册方法
  const onSwipe = (direction: keyof typeof swipeCallbacks, callback: Function) => {
    swipeCallbacks[direction].push(callback)
  }

  const onPinch = (type: keyof typeof pinchCallbacks, callback: Function) => {
    pinchCallbacks[type].push(callback)
  }

  const onTap = (type: keyof typeof tapCallbacks, callback: Function) => {
    tapCallbacks[type].push(callback)
  }

  // 移除事件方法
  const offSwipe = (direction: keyof typeof swipeCallbacks, callback: Function) => {
    const index = swipeCallbacks[direction].indexOf(callback)
    if (index > -1) {
      swipeCallbacks[direction].splice(index, 1)
    }
  }

  const offPinch = (type: keyof typeof pinchCallbacks, callback: Function) => {
    const index = pinchCallbacks[type].indexOf(callback)
    if (index > -1) {
      pinchCallbacks[type].splice(index, 1)
    }
  }

  const offTap = (type: keyof typeof tapCallbacks, callback: Function) => {
    const index = tapCallbacks[type].indexOf(callback)
    if (index > -1) {
      tapCallbacks[type].splice(index, 1)
    }
  }

  // 启用手势
  const enableGestures = () => {
    if (!element.value) return

    element.value.addEventListener('touchstart', handleTouchStart, { passive: false })
    element.value.addEventListener('touchmove', handleTouchMove, { passive: false })
    element.value.addEventListener('touchend', handleTouchEnd, { passive: false })
    element.value.addEventListener('touchstart', handleLongPress, { passive: false })
    element.value.addEventListener('touchmove', () => clearTimeout(longPressTimeout), { passive: false })
    element.value.addEventListener('touchend', () => clearTimeout(longPressTimeout), { passive: false })

    // 添加 CSS 样式
    if (element.value.style) {
      element.value.style.touchAction = 'none'
      element.value.style.userSelect = 'none'
      element.value.style.position = 'relative'
    }
  }

  // 禁用手势
  const disableGestures = () => {
    if (!element.value) return

    element.value.removeEventListener('touchstart', handleTouchStart)
    element.value.removeEventListener('touchmove', handleTouchMove)
    element.value.removeEventListener('touchend', handleTouchEnd)
    element.value.removeEventListener('touchstart', handleLongPress)
    
    clearTimeout(tapTimeout)
    clearTimeout(longPressTimeout)
  }

  // 生命周期
  onMounted(() => {
    if (element.value) {
      enableGestures()
    }
  })

  onUnmounted(() => {
    disableGestures()
  })

  return {
    // 状态
    isTouch,
    touchDistance,
    touchAngle,
    currentScale,
    
    // 事件注册
    onSwipe,
    onPinch,
    onTap,
    
    // 事件移除
    offSwipe,
    offPinch,
    offTap,
    
    // 控制方法
    enableGestures,
    disableGestures,
  }
}
